/* a client in the unix domain */
#include <sys/socket.h>
#include <sys/un.h>
#include <iostream>
#include "../MessageAsset/Message.h"

#define SERVER_ADDRESS "/Users/macos2/Desktop/server_socket"
#define CLIENT_ADDRESS "/Users/macos2/Desktop/client_socket"

using namespace std;

void error(const char *);

int main(int argc, char *argv[])
{
    int sockfd, n;
    socklen_t socklen;
    struct sockaddr_un server_address, client_address;

    bzero(&server_address, sizeof (server_address));
    server_address.sun_family = AF_UNIX;
    strcpy(server_address.sun_path, SERVER_ADDRESS);

    bzero(&client_address, sizeof (client_address));
    client_address.sun_family = AF_UNIX;
    strcpy(client_address.sun_path, CLIENT_ADDRESS);

    if ((sockfd = socket(AF_UNIX, SOCK_DGRAM, 0)) < 0) error("Creating socket");
    socklen = sizeof (struct sockaddr_un);
    unlink(CLIENT_ADDRESS);
    if (bind(sockfd, (struct sockaddr*) & client_address, socklen) < 0) error("binding cli socket");
    do
    {
        struct Message msg;
        msg.char_val = 'T';
        msg.int_val = 25;
        msg.float_val = 2.5;
        msg.double_val = 7.6L;
        strcpy(msg.content, "Victory");

        n = sendto(sockfd, &msg, sizeof(msg), 0, (sockaddr*) & server_address, socklen);
        if (n < 0) error("sendto");
        printf("sent %d bytes\n", n);

        char receive_buffer[1024] = {0};
        n = recvfrom(sockfd, receive_buffer, 1024, 0, (sockaddr*) & server_address, &socklen);
        if (n < 0) error("recvfrom");
        printf("received %d bytes\n", n);
        printf("Got an ack: %s\n", receive_buffer);

        break;
    } while (1);

    close(sockfd);
    return 0;
}

void error(const char *msg)
{
    perror(msg);
    exit(0);
}
